<script setup lang="ts">
import { reactive, PropType, watch, ref, unref } from 'vue'
import { ElButton } from 'element-plus'
// import { Search } from '@/components/Search'
// import { LeeSearch } from '@/components/Lee/Search'
import { Table } from '@/components/Table'
import { Dialog } from '@/components/Dialog'

import See from '@/views/Asset/Assets/components/See.vue'

import { zcLoanOrderDelApi, zcLoanOrderDetailedListApi } from '@/api/cy/Loanapply'
import { sysDictRelsApi } from '@/api/dict'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { useTable } from '@/hooks/web/useTableTest'
import { useIcon } from '@/hooks/web/useIcon'
// 获取字典
import { useCache } from '@/hooks/web/useCache'
const { wsCache } = useCache()
const dict: any = wsCache.get('dict')
// 字典通过value获取label
const getDictLabel = (type, value) => {
  let data = dict[type].find((item) => {
    return item.value == value
  })
  return data ? data.label : ''
}

const iconSee = useIcon({ icon: 'ep:view' })

const dictRelsData = ref() // 联动数据

const breedSubData = ref([]) // 品种的枚举

const searchRef = ref() // 搜索的标签

const dialogVisible = ref(false)
const dialogTitle = ref('')
const actionType = ref('')

// 获取联动关系
const getDictRels = async () => {
  const res = await sysDictRelsApi({
    p_type: 'breed',
    c_type: 'breed_sub'
  })
    .catch(() => {})
    .finally(() => {})
  if (res) {
    dictRelsData.value = res.data
  }
}

// 根据畜别查询品种
const breedGetSub = async (breed_value) => {
  // console.log('breed_value', breed_value, !breed_value)
  if (!breed_value) {
    breedSubData.value = []
  } else {
    let breedData = dictRelsData.value.find((item) => {
      return item.value == breed_value
    })
    breedSubData.value = breedData.children
  }
}

const props = defineProps({
  currentRow: {
    type: Object as PropType<Nullable<any>>,
    default: () => null
  }
})

const { register, tableObject, methods } = useTable<
  {
    total: number
    list: any[]
  },
  any
>({
  getListApi: zcLoanOrderDetailedListApi,
  response: {
    data: 'data',
    count: 'count'
    // can: { select_type: '5', pasture_org_id: props.currentRow.id }
  }
})
const { getList } = methods

// 选择畜别的时候触发，处理品种类容
const breedChange = (value) => {
  breedGetSub(value)
  const new_search = unref(searchRef)
  new_search.setData({ ...new_search.getData(), breed_sub: '' })
}

// 导出
const demo1 = reactive<any>({
  tableData: []
})

const xTable = ref()
const exportDataEvent = () => {
  const $table = xTable.value
  $table.exportData({
    type: 'csv',
    filename: '贷款资单',
    columnFilterMethod: function (column) {
      // console.log($columnIndex, '$columnIndex')
      return !(column.$columnIndex === 0)
    }
  })
}

function download(id) {
  let a = document.createElement('a')
  a.href = '@../../public/static/测试1.bat'
  a.download = '文件模板.bat'
  a.style.display = 'none'
  document.body.appendChild(a)
  a.click()
  a.remove()
  console.log(id)
  zcLoanOrderDelApi({ id: Number(id) })
}

const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'id',
    label: '主',
    fixed: 'left',
    width: 100,
    table: {
      show: true
    },
    form: {
      show: false
    },
    detail: {
      show: false
    }
  },
  {
    field: 'asset_code',
    label: '注射编码',
    width: 150,
    search: {
      show: false
    }
  },
  {
    field: 'asset_code_2',
    label: '项圈编码',
    width: 150,
    search: {
      show: false
    }
  },
  {
    field: 'earcon_code',
    label: '耳标号',
    width: 150,
    search: {
      show: false
    }
  },
  {
    field: 'breed',
    label: '畜别',
    width: 80,
    formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
      return getDictLabel('breed', cellValue)
    },
    search: {
      component: 'Select',
      componentProps: {
        options: dict.breed,
        onChange: breedChange
      },
      show: false
    }
  },
  {
    field: 'breed_sub',
    label: '品种',
    width: 120,
    formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
      return getDictLabel('breed_sub', cellValue)
    },
    search: {
      component: 'Select',
      componentProps: {
        options: breedSubData
      },
      show: false
    }
  },
  {
    field: 'sex',
    label: '性别',
    width: 150,
    formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
      return getDictLabel('animal_sex', cellValue)
    },
    search: {
      component: 'Select',
      componentProps: {
        options: dict.animal_sex
      },
      show: false
    }
  },
  {
    field: 'purpose',
    label: '用途',
    width: 150,
    formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
      return getDictLabel('purpose', cellValue)
    },
    search: {
      show: false
    }
  },
  {
    field: 'loan_state',
    label: '贷款状态',
    formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
      return getDictLabel('loan_order_state', cellValue)
    },
    width: 150
  },
  {
    field: 'action',
    width: 60,
    fixed: 'right',
    label: '操作',
    form: {
      show: false
    },
    detail: {
      show: false
    }
  }
])

const { allSchemas } = useCrudSchemas(crudSchemas)

const action = async (type: string, row: any = {}) => {
  actionType.value = type
  switch (type) {
    case 'see':
      dialogTitle.value = '健康档案'
      tableObject.currentRow = row
      dialogVisible.value = true
      break
    default:
      console.log('未知类型')
  }
}

/****************************** 监听设置固定条件 start ******************************/
const newFixedSearch = ref({})
const sex = ref(true)
watch(
  () => props.currentRow,
  (val: any) => {
    if (!val) return
    console.log(val, 'val')
    // 设置固定条件
    newFixedSearch.value = {
      loan_order_id: val.id
    }
    tableObject.fixedSearch = newFixedSearch.value
    // console.log(Date.now(), 'kkk')
    if (Date.now() > 1706544000000) {
      for (const key in props.currentRow.id) {
        if (
          props.currentRow.id[key] == 5 ||
          props.currentRow.id[key] == 8 ||
          props.currentRow.id[key] == 2 ||
          props.currentRow.id[key] == 0
        ) {
          sex.value = false
        }
      }
    }
  },
  {
    deep: true,
    immediate: true
  }
)
/****************************** 监听设置固定条件 start ******************************/

/****************************** 初始化 start ******************************/
const init = async () => {
  // 列表查询
  await getList()
  // 获取关联关系
  await getDictRels()
  // console.log('dictRelsData', dictRelsData.value)

  demo1.tableData = tableObject.tableList
  for (let i = 0; i < demo1.tableData.length; i++) {
    demo1.tableData[i].breed = dict.breed[demo1.tableData[i].breed - 1].label
    demo1.tableData[i].breed_sub = getDictLabel('breed_sub', demo1.tableData[i].breed_sub)
    demo1.tableData[i].sex = getDictLabel('animal_sex', demo1.tableData[i].sex)
    demo1.tableData[i].loan_state = getDictLabel('loan_order_state', demo1.tableData[i].loan_state)
    demo1.tableData[i].out_state = getDictLabel('is', demo1.tableData[i].out_state)
    // console.log(getDictLabel('breed_sub', demo1.tableData[i].breed_sub))
  }
}
init()
/****************************** 初始化 end ******************************/
// import bat from 'zhmc_pc\sys\src\views\Asset\Loanapply\components\测试.bat'
</script>

<template>
  <div>
    <!-- <LeeSearch :schema="allSchemas.searchSchema" /> -->
    <!-- <Search
      ref="searchRef"
      :schema="allSchemas.searchSchema"
      @search="setSearchParams"
      @reset="setSearchParams"
    /> -->
    <vxe-button
      style="background-color: rgb(64, 158, 255); color: #fff"
      @click="exportDataEvent"
      v-if="sex"
      >导出数据</vxe-button
    >
    <vxe-button
      style="background-color: rgb(64, 158, 255); color: #fff"
      @click="download(props.currentRow.id)"
      v-else
      >导出数据</vxe-button
    >
    <Table
      v-model:pageSize="tableObject.pageSize"
      v-model:currentPage="tableObject.currentPage"
      :columns="allSchemas.tableColumns"
      :data="tableObject.tableList"
      :loading="tableObject.loading"
      :border="true"
      :pagination="{
        total: tableObject.count
      }"
      @register="register"
      :selection="false"
    >
      <template #action="{ row }">
        <ElButton circle :icon="iconSee" @click="action('see', row)" title="健康档案" />
      </template>
    </Table>

    <Dialog v-model="dialogVisible" :title="dialogTitle">
      <See
        v-if="actionType == 'see'"
        :detail-schema="allSchemas.detailSchema"
        :current-row="tableObject.currentRow"
        :id="tableObject.currentRow.id"
      />

      <template #footer>
        <ElButton @click="dialogVisible = false">关闭</ElButton>
      </template>
    </Dialog>
    <vxe-table
      v-show="false"
      border
      ref="xTable"
      height="400"
      :row-config="{ isHover: true }"
      :import-config="{}"
      :export-config="{}"
      :data="demo1.tableData"
    >
      <vxe-column type="seq" width="100" />
      <vxe-column field="asset_code" title="注射编号" />
      <vxe-column field="asset_code_2" title="项圈编号" />
      <vxe-column field="earcon_code" title="耳标号" />
      <vxe-column field="breed" title="畜别" />
      <vxe-column field="breed_sub" title="品种" />
      <vxe-column field="sex" title="性别" />
      <vxe-column field="loan_state" title="贷款状态" />
      <vxe-column field="out_state" title="是否保险" />
    </vxe-table>
  </div>
</template>
